package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.hmdp.constant.MessageConstant.ID_NOT_EMPTY;
import static com.hmdp.constant.MessageConstant.SHOP_NOT_EXIST;
import static com.hmdp.constant.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.constant.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryShopById(Long id) {
        //判断redis中是否存在店铺信息
        String jsonShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //存在，直接取出数据并返回
        if(StrUtil.isNotBlank(jsonShop)){//不为null或空
            return Result.ok(JSONUtil.toBean(jsonShop, Shop.class));
        }
        //不存在，查数据库
        Shop shop = getById(id);
        //数据库中也不存在店铺的信息,返回错误
        if(shop == null){
            return Result.fail(SHOP_NOT_EXIST);
        }
        //存在，把数据放入redis，并返回数据给前端
        String jsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,jsonStr,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    /**
     * 2025/07/16
     * 更新商铺信息
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        if(shop.getId() == null){
            return Result.fail(ID_NOT_EMPTY);
        }
        //更新数据库
        updateById(shop);
        //删除redis对应数据
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
